import Taro from '@tarojs/taro'
import { API_BASE_URL } from '../../../config/env'

const BASE_URL = `${API_BASE_URL}/api`
const TIMEOUT = 30000

// 请求拦截器 - 添加token
const addAuthHeader = () => {
    try {
        const token = Taro.getStorageSync('token')
        return token ? {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        } : {
            'Content-Type': 'application/json'
        }
    } catch (error) {
        console.log('获取token失败:', error)
        return {
            'Content-Type': 'application/json'
        }
    }
}

// 通用请求方法
const request = async (options: {
    url: string
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
    data?: any
    header?: any
}) => {
    const { url, method = 'GET', data, header = {} } = options

    try {
        const authHeader = addAuthHeader()
        const fullUrl = url.startsWith('http') ? url : `${BASE_URL}${url}`


        const response = await Taro.request({
            url: fullUrl,
            method,
            data,
            header: {
                ...authHeader,
                ...header
            },
            timeout: TIMEOUT
        })


        // 检查HTTP状态码
        if (response.statusCode >= 200 && response.statusCode < 300) {
            return response.data
        } else {
            throw new Error(`HTTP ${response.statusCode}: ${response.data?.message || '请求失败'}`)
        }

    } catch (error: any) {
        console.error('请求失败:', error)

        // 处理不同类型的错误
        if (error.errMsg) {
            // Taro请求错误
            if (error.errMsg.includes('timeout')) {
                throw new Error('网络请求超时，请检查网络连接')
            } else if (error.errMsg.includes('fail')) {
                throw new Error('网络连接失败，请检查服务器状态')
            }
        }

        throw error
    }
}

// 封装常用的请求方法
export const api = {
    get: (url: string, params?: any) => {
        const queryString = params ?
            '?' + Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&') : ''
        return request({
            url: url + queryString,
            method: 'GET'
        })
    },

    post: (url: string, data?: any) => {
        return request({
            url,
            method: 'POST',
            data
        })
    },

    put: (url: string, data?: any) => {
        return request({
            url,
            method: 'PUT',
            data
        })
    },

    delete: (url: string) => {
        return request({
            url,
            method: 'DELETE'
        })
    }
}

export default api